package hander

import (
	"context"
	"week4/retailers/srv-server/basic/global"
	"week4/retailers/srv-server/internal/dao"
	"week4/retailers/srv-server/internal/model"

	__ "week4/retailers/srv-server/proto"
)

type UserServer struct {
	__.UnimplementedUserServer
}

func (c *UserServer) List(_ context.Context, in *__.ListRequest) (*__.ListResponse, error) {
	var list []model.Retailer
	var listli []*__.ListRank
	page := in.Page
	if page <= 0 {
		page = 1
	}

	pageSize := in.Size
	switch {
	case pageSize > 100:
		pageSize = 100
	case pageSize <= 0:
		pageSize = 10
	}

	offset := (page - 1) * pageSize
	global.DB.Order("price desc").Offset(int(offset)).Limit(int(pageSize)).Find(&list)

	for _, r := range list {
		listli = append(listli, &__.ListRank{
			Id:        int64(r.ID),
			Name:      r.Name,
			Price:     int64(r.Price),
			Num:       int64(r.Num),
			Address:   r.Address,
			SendPhone: r.SendPhone,
			Recipient: r.Recipient,
		})

	}

	return &__.ListResponse{List: listli}, nil

}
func (c *UserServer) Info(_ context.Context, in *__.InfoRequest) (*__.InfoResponse, error) {

	var user model.Retailer

	if err := global.DB.Where("id = ?", in.Id).First(&user).Error; err != nil {
		return nil, err
	}

	return &__.InfoResponse{
		Id:        int64(user.ID),
		Name:      user.Name,
		Price:     int64(user.Price),
		Num:       int64(user.Num),
		Address:   user.Address,
		SendPhone: user.SendPhone,
		Recipient: user.Recipient,
	}, nil

}
func (c *UserServer) Add(_ context.Context, in *__.AddRequest) (*__.AddResponse, error) {

	dao.Create(&model.Retailer{
		Name:      in.Name,
		Price:     int(in.Price),
		Num:       int(in.Num),
		Address:   in.Address,
		SendPhone: in.SendPhone,
		Recipient: in.Recipient,
	})

	return &__.AddResponse{
		Code:    200,
		Message: "添加成功",
	}, nil

}
